﻿/*******************************************************************************
 * AAEngine
 * Copyright (c) 2010 Mike Jarosch
 *
 * Original source PushButton Engine:
 * Copyright (C) 2009 PushButton Labs, LLC
 * For more information see http://www.pushbuttonengine.com
 *
 * This file is licensed under the terms of the MIT license, which is included
 * in the "MIT License.txt" file at the root directory of this SDK.
 ******************************************************************************/

using System;
using Microsoft.Xna.Framework;
using AAEngine.Engine;
using AAEngine.Engine.Resources;

namespace AAEngine.Rendering2D.Renderers
{
    public class SpriteRenderer : ImageRenderer
    {
        private string _filename;
        private ImageResource _resource;

        public string Filename
        {
            get { return _filename; }
            set
            {
                if (_filename != value)
                {
                    if (_resource != null)
                    {
                        AAGame.ResourceManager.Unload(_resource.Filename);

                        _resource = null;
                    }
                    _filename = value;
                    _resource = (ImageResource)AAGame.ResourceManager.Load(value, typeof(ImageResource));

                    RegistrationPoint = new Vector2(_resource.ImageData.Width / 2, _resource.ImageData.Height / 2);
                    ImageData = _resource.ImageData;
                }
            }
        }

        public override void OnAdd()
        {
            base.OnAdd();

            if (_resource == null && !String.IsNullOrEmpty(_filename))
            {
                _resource = (ImageResource)AAGame.ResourceManager.Load(_filename, typeof(ImageResource));
            }
        }

        public override void OnRemove()
        {
            if (_resource != null)
            {
                AAGame.ResourceManager.Unload(_resource.Filename);
                _resource = null;
            }
            base.OnRemove();
        }
    }
}
